<template>
    <div class="goods-add-form">
        <!-- 基础信息区域 -->
        <div class="section">
            <h2 class="section-title">基础信息</h2>
            <el-form ref="ruleFormRef" style="max-width: 1200px;margin: 20px;" :model="pro" status-icon :rules="rules"
                label-width="auto" class="demo-ruleForm">
                <el-form-item label="产品名称" prop="pro_name">
                    <el-input v-model.number="pro.pro_name" placeholder="产品名称" />
                </el-form-item>

                <div style="display: flex; justify-content: space-between;">
                    <div style="width: 48%;">
                        <el-form-item prop="" label="产品编号" style="margin-bottom: 30px;">
                            <el-input v-model.number="pro.pro_code" placeholder="自动获取编号" disabled />
                        </el-form-item>
                        <el-form-item label="计量单位" prop="measure_id" style="margin-bottom: 30px;">
                            <el-select v-model="pro.measure_id" placeholder="计量单位">
                                <el-option v-for="item in measureOptios" :key="item.dict_value" :label="item.dict_label"
                                    :value="item.dict_value" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="规格型号" prop="" style="margin-bottom: 30px;">
                            <el-input v-model="pro.pro_model" placeholder="规格型号" clearable />
                        </el-form-item>
                        <el-form-item prop="" label="产品品牌" style="margin-bottom: 30px;">
                            <el-input v-model="pro.pro_brand" placeholder="产品品牌" clearable />
                        </el-form-item>
                        <el-form-item prop="pro_cost_price" label="成本单价" style="margin-bottom: 30px;">
                            <el-input v-model="pro.pro_cost_price" placeholder="成本单价"
                                :formatter="(value) => `$ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
                                :parser="(value) => value.replace(/\$\s?|(,*)/g, '')" />
                        </el-form-item>

                        <el-form-item prop="" label="产品状态" style="margin-bottom: 30px;">
                            <el-radio-group v-model="pro.pro_status">
                                <el-radio value="0">正常</el-radio>
                                <el-radio value="1">停用</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </div>

                    <div style="width: 48%;">
                        <el-form-item label="产品类型" prop="pro_type_code" style="margin-bottom: 30px;">
                            <el-tree-select v-model="pro.pro_type_code" :data="data" placeholder="产品类型"
                                :props="treeProps" clearable check-strictly />
                        </el-form-item>
                        <el-form-item prop="pro_attribute_id" label="产品属性" style="margin-bottom: 30px;">
                            <el-select v-model="pro.pro_attribute_id" placeholder="产品属性">
                                <el-option v-for="item in attributeOptios" :key="item.dict_value"
                                    :label="item.dict_label" :value="item.dict_value" />
                            </el-select>
                        </el-form-item>
                        <el-form-item prop="pro_sort" label="产品排序" style="margin-bottom: 30px;">
                            <el-input v-model="pro.pro_sort" placeholder="排序" clearable />
                        </el-form-item>
                        <el-form-item prop="pro_sale_price" label="销售单价" style="margin-bottom: 30px;">
                            <el-input v-model="pro.pro_sale_price" placeholder="销售单价"
                                :formatter="(value) => `$ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
                                :parser="(value) => value.replace(/\$\s?|(,*)/g, '')" />
                        </el-form-item>
                        <el-form-item prop="" label="销售毛利" style="margin-bottom: 30px;">
                            <el-input v-model="pro.pro_grossMargin" placeholder="销售毛利"
                                :formatter="(value) => `$ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
                                :parser="(value) => value.replace(/\$\s?|(,*)/g, '')" readonly />
                        </el-form-item>
                        <el-form-item prop="pro_shelf_life" label="产品保质期" style="margin-bottom: 30px;">
                            <!-- <el-date-picker v-model="pro.pro_shelf_life" type="date" placeholder="产品保质期" :size="size"
                                style="width: 465px;" /> -->
                            <el-input v-model="pro.pro_shelf_life" placeholder="产品保质期" clearable
                                style="width: 365px;" />
                            <el-select v-model="shelf_life_value" placeholder="Select"
                                style="width: 80px;margin-left: 20px;">
                                <el-option v-for="item in options" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </div>
                </div>
            </el-form>
        </div>

        <div class="section">
            <h2 class="section-title">上传图片</h2>
            <div class="img-title">
                <span>
                    您可以上传png, jpg, gif等格式的文件，单个图片最大不能超过10MB，最多可上传10张。
                </span>
            </div>
            <el-upload action="#" list-type="picture-card" :auto-upload="false" v-model:file-list="fileList" :limit="10"
                @remove="handleRemove" @change="handleChange" accept="image/jpeg,image/jpg,image/png,,image/gif"
                :limit-size="10240" style="margin-left: 35px;text-align: left;margin-top: 10px;"
                :before-upload="beforeAvatarUpload">
                <el-icon>
                    <Plus />
                </el-icon>
                <template #file="{ file }">
                    <div>
                        <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                        <span class="el-upload-list__item-actions">
                            <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                                <el-icon><zoom-in /></el-icon>
                            </span>
                            <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleDownload(file)">
                                <el-icon>
                                    <Download />
                                </el-icon>
                            </span>
                            <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
                                <el-icon>
                                    <Delete />
                                </el-icon>
                            </span>
                        </span>
                    </div>
                </template>
            </el-upload>

            <el-dialog v-model="dialogVisible">
                <img w-full :src="dialogImageUrl" alt="Preview Image" />
            </el-dialog>
        </div>

        <!-- 底部操作按钮 -->
        <div class="button-group" style="position: absolute; bottom: 10px; right: 64px; display: flex; gap: 10px;">
            <el-button type="primary" @click="proAdd">保存</el-button>
            <el-button @click="pro_handleClose">关闭</el-button>
        </div>
    </div>
</template>

<script>
import { ref, reactive, onMounted, watch, inject } from 'vue';
import axios from 'axios';
import dayjs from 'dayjs'
import { ElMessage, ElLoading } from 'element-plus';
import { useRouter } from 'vue-router';
export default {
    setup() {
        const data = ref([])
        const ruleFormRef = ref(null)
        const rules = reactive({
            pro_name: [
                { required: true, message: "产品名称不能为空", trigger: ["blur","change"] },
            ],
            pro_type_code: [
                { required: true, message: "产品类型不能为空", trigger: ["blur","change"] },
            ],
            measure_id: [
                { required: true, message: "计量单位不能为空", trigger: ["blur","change"] },
            ],
            pro_attribute_id: [
                { required: true, message: "产品属性不能为空", trigger: ["blur","change"] },
            ],
            pro_sort: [
                { required: true, message: "产品排序不能为空", trigger: ["blur","change"] },
            ],
            pro_sale_price: [
                { required: true, message: "销售单价不能为空", trigger: ["blur","change"] },
            ],
            pro_model: [
                { required: true, message: "产品规格型号不能为空", trigger: ["blur","change"] },
            ],
            pro_brand: [
                { required: true, message: "产品品牌不能为空", trigger: ["blur","change"] },
            ],
            pro_cost_price: [
                { required: true, message: "成本单价不能为空", trigger: ["blur","change"] },
            ],
            pro_shelf_life: [
                { required: true, message: "产品保质期不能为空", trigger: ["blur","change"] },
            ]
        });
        const pro = reactive({
            pro_name: "",//产品名称
            pro_code: "",//产品编号
            pro_type_code: "",//产品分类编号
            measure_id: "",//计量单位
            pro_attribute_id: "",//产品属性
            pro_model: "",//规格型号
            pro_sort: "",//产品排序
            pro_brand: "",//产品品牌
            pro_sale_price: "",//销售单价
            pro_cost_price: "",//成本单价
            pro_shelf_life: "",//产品保质期
            pro_grossMargin: "",//销售毛利
            pro_status: "0",//产品状态
        });
        const attachmentFileAddDto = ref([])
        const pro_code = ref("")
        const router = useRouter();
        const shelf_life_value = ref("天")
        const options = [{
            value: "天",
            label: "天"
        }, {
            value: "月",
            label: "月"
        }, {
            value: "年",
            label: "年"
        }]

        const fileList = ref([]); // 存储上传的文件列表
        const dialogVisible = ref(false);
        const dialogImageUrl = ref('');
        const currentFile = ref(null);
        const attributeOptios = ref([])
        const measureOptios = ref([])

        onMounted(() => {
            pro_type_Opt()
            getAttribute()
            getMeasure()
        })

        //监听值变化
        watch(() => [pro.pro_cost_price, pro.pro_sale_price], ([cost, sale]) => {
            // 将字符串转换为数字，注意可能是空字符串
            const costNum = parseFloat(cost) || 0;
            const saleNum = parseFloat(sale) || 0;
            const grossMargin = saleNum - costNum;
            // 将计算结果赋值给pro.pro_grossMargin，注意我们只需要数字字符串（因为formatter会处理显示）
            pro.pro_grossMargin = grossMargin.toString();
        });

        function pro_type_Opt() {
            axios.get("http://localhost:5181/api/Product_Type/GetProduct_Types", {
                params: {
                    currentPage: 0,
                    pageSize: 0,
                    typeName: "",
                    status: '0'
                }, headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                data.value = convertToTreeOptions(result.data)
            }).catch((err) => {
                console.info(err)
            });
        }

        const convertToTreeOptions = (items) => {
            return items.map(item => ({
                value: item.pro_type_code,
                pro_type_code: item.pro_type_code,
                label: item.pro_type_name,
                children: item.children && item.children.length > 0
                    ? convertToTreeOptions(item.children)
                    : []
            }))
        }

        function getAttribute() {
            axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
                params: {
                    dict_type: "db_pro_attribute"
                }, headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                attributeOptios.value = result.data
            }).catch((err) => {
                console.info(err)
            });
        }

        function getMeasure() {
            axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
                params: {
                    dict_type: "db_measure"
                }, headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                measureOptios.value = result.data
            }).catch((err) => {
                console.info(err)
            });
        }

        // 处理文件移除
        const handleRemove = (file) => {
            console.log('移除文件:', file);
            fileList.value = fileList.value.filter(item => item.uid !== file.uid);
        };

        // 处理图片预览
        const handlePictureCardPreview = (file) => {
            dialogImageUrl.value = file.url || '';
            currentFile.value = file;
            dialogVisible.value = true;
        };

        const handleChange = (file) => {
            // 为每个文件生成唯一ID
            file.uid = URL.createObjectURL(file.raw);
            fileList.value.push(file);
        };

        // 处理文件下载
        const handleDownload = (file) => {
            console.log('下载文件:', file);
            if (file.url) {
                window.open(file.url, '_blank');
            }
        };

        const beforeAvatarUpload = (rawFile) => {
            const allowedExtensions = ['.jpg', '.jpeg']; // 只允许 JPG/JPEG
            const fileExtension = rawFile.name.substring(rawFile.name.lastIndexOf('.')).toLowerCase();

            if (!allowedExtensions.includes(fileExtension)) {
                ElMessage.error('只能上传 JPG/JPEG 格式的图片！');
                return false; // 阻止上传
            }

            const maxSizeMB = 10;
            if (rawFile.size > maxSizeMB * 1024 * 1024) {
                ElMessage.error(`图片大小不能超过 ${maxSizeMB}MB！`);
                return false;
            }

            return true; // 允许上传
        };

        async function proAdd() {
            ruleFormRef.value.validate(async (valid, fields) => {
                if (valid) {
                    // const isSortUnique = await CheckSortUnique(pro.pro_sort);
                    // if (isSortUnique) {
                    //     // 如果排序序号不唯一，直接退出方法
                    //     return;
                    // }
                    //如果排序序号唯一，继续执行后续逻辑
                    if (pro.pro_code == "") {
                        // 如果产品编号为空，自动获取编号
                        obtainCode().then(() => {
                            add();
                        }).catch((err) => {
                            console.info(err);
                        });
                    } else {
                        // 如果产品编号已填写，直接添加产品信息
                        add();
                    }
                }
            })
        }

        async function add() {
            const loadingInstance = ElLoading.service({
                lock: true,
                text: '正在添加中...',
                background: 'rgba(0, 0, 0, 0.7)',
            });

            try {
                if (shelf_life_value.value === '月') {
                    pro.pro_shelf_life = pro.pro_shelf_life * 30
                } else if (shelf_life_value.value === '年') {
                    pro.pro_shelf_life = pro.pro_shelf_life * 365
                }
                const result = await axios.post("http://localhost:5181/api/Db_Product/ProductAdd", {
                    measure_id: pro.measure_id,
                    pro_name: pro.pro_name,
                    pro_code: pro.pro_code,
                    pro_attribute_id: pro.pro_attribute_id,
                    pro_type_code: pro.pro_type_code,
                    pro_sort: pro.pro_sort,
                    pro_brand: pro.pro_brand,
                    pro_model: pro.pro_model,
                    pro_cost_price: pro.pro_cost_price,
                    pro_sale_price: pro.pro_sale_price,
                    pro_grossMargin: pro.pro_grossMargin,
                    pro_shelf_life: pro.pro_shelf_life,
                    pro_status: pro.pro_status,
                    del_flag: '0',
                    create_by: localStorage.getItem('userLName'),
                    create_time: dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ')
                }, {
                    headers: {
                        authorization: `Bearer ${localStorage.getItem('token')}`
                    }
                });

                pro_code.value = result.data; // 赋值
                console.log('result.data:', pro_code.value); // 打印 result.data
                await addFile(); // 确保在赋值之后调用addFile

                ElMessage({
                    type: 'success',
                    message: '产品信息添加成功！'
                });
                pro_handleClose()
            } catch (err) {
                console.info(err);
            } finally {
                loadingInstance.close();
            }
        }

        async function addFile() {
            const formData = new FormData();

            // 把文件添加到formData中
            fileList.value.forEach(file => {
                if (file.raw) {
                    formData.append('formFiles', file.raw);
                }
            });

            try {
                const result = await axios.post("http://localhost:5181/api/Db_Attachmet/UploadMultipleAvatars",
                    formData, {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                });

                attachmentFileAddDto.value = result.data.fileName.map((fileName, index) => ({
                    document_type: 1,
                    document_code: pro.pro_code, // 使用赋值后的pro_code.value
                    file_name: fileName,
                    file_type: result.data.fileType[index],
                    file_address: result.data.paths[index],
                    file_size: result.data.fileSize[index]
                }));

                await addAttachmet();
            } catch (err) {
                console.error(err);
            }
        }

        async function addAttachmet() {
            console.info(attachmentFileAddDto)
            const attachmentFileAddDtoArray = attachmentFileAddDto.value;

            // 遍历数组并打印每个元素
            for (var i = 0; i < attachmentFileAddDtoArray.length; i++) {
                console.info(attachmentFileAddDtoArray[i].document_code);
                axios.post("http://localhost:5181/api/Db_Attachmet/AttachmetAdd", {
                    document_type: attachmentFileAddDtoArray[i].document_type,
                    document_code: attachmentFileAddDtoArray[i].document_code,
                    file_name: attachmentFileAddDtoArray[i].file_name,
                    file_type: attachmentFileAddDtoArray[i].file_type,
                    file_address: attachmentFileAddDtoArray[i].file_address,
                    file_size: attachmentFileAddDtoArray[i].file_size
                }, {
                    headers: {
                        authorization: `Bearer ${localStorage.getItem('token')}`
                    }
                }).then((result) => {
                    console.info(result.data)
                }).catch((err) => {
                    console.info(err)
                });
            }
        }

        function CheckSortUnique(sort) {
            return new Promise((resolve, reject) => {
                axios.get("http://localhost:5181/api/Db_Product/CheckSortUnique", {
                    params: {
                        sort: sort,
                        proId: 0
                    },
                    headers: {
                        authorization: `Bearer ${localStorage.getItem('token')}`
                    }
                }).then((result) => {
                    if (result.data) {
                        ElMessage.error('该排序序号已存在！');
                        resolve(true); // 排序序号不唯一
                    } else {
                        resolve(false); // 排序序号唯一
                    }
                }).catch((err) => {
                    console.info(err);
                    resolve(true); // 发生错误时，假设排序序号不唯一
                });
            });
        }

        function obtainCode() {
            return axios.get("http://localhost:5181/api/DJBH/DJBH", {
                params: {
                    en_code: 2
                }
            }).then((result) => {
                pro.pro_code = result.data
            }).catch((err) => {
                console.info(err)
            });
        }

        // function pro_handleClose() {
        //     router.push("/main/DB/ProductInfo")
        // }

        const closeTab = inject('closeTab'); // 注入关闭方法
        const pro_handleClose = () => {
            const targetPath = "/main/DB/ProductInfo";

            if (closeTab) {
                closeTab(); // 调用父组件提供的关闭方法
            }

            // 添加目标标签页（如果不存在）
            const tabs = inject('editableTabs');
            if (tabs && !tabs.value.some(tab => tab.path === targetPath)) {
                tabs.value.push({
                    title: "产品信息",
                    name: targetPath,
                    path: targetPath
                });
            }

            // 跳转并激活目标标签页
            const activeTab = inject('editableTabsValue');
            if (activeTab) {
                activeTab.value = targetPath;
            }

            router.push(targetPath);
        };

        return {
            pro,
            fileList,
            dialogVisible,
            dialogImageUrl,
            currentFile,
            handleRemove,
            handlePictureCardPreview,
            handleDownload, handleChange, beforeAvatarUpload, data, measureOptios, attributeOptios, proAdd, ruleFormRef, rules, pro_handleClose,
            options, shelf_life_value
        };
    }
};
</script>


<style scoped>
.draggable-item {
    transition: all 0.3s;
}

.dragging {
    opacity: 0.5;
    transform: scale(0.95);
}

.drag-over {
    outline: 2px dashed #409eff;
    outline-offset: 5px;
}

.goods-add-form {
    padding: 20px;
    background-color: #fff;
}

.section {
    margin-bottom: 30px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    padding: 20px;
    /* 添加阴影效果 */
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.section-title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 15px;
}

.inner-form {
    background-color: #fff;
}

.button-group {
    float: right;
    display: flex;
    position: flex;
    text-align: right;
    margin-top: 20px;
    height: 7%;
    align-items: center;
    width: 80.1%;
    background-color: #ffffff;
    justify-content: flex-end;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    padding-right: 20px;
}

.img-title {
    /* display: flex;
    left: 60px; */
    margin-left: -390px;
    color: #99b3d4;
    font-size: 15px;
}
</style>